#!/bin/bash

# Provide source directive to shellcheck.
# shellcheck source=meta-facebook/meta-greatlakes/recipes-phosphor/state/phosphor-state-manager/power-cmd
source /usr/libexec/phosphor-state-manager/power-cmd

SLOT=$(( $1-1 ))
OFFSET=$(( 0x9 + SLOT ))

chassis-power-cycle()
{
    CHASSIS_ID=$1

    if [ "$CHASSIS_ID" -le 4  ]
    then
        chassis_status=$(chassis-power-status $SLOT)
        if [ "$chassis_status" == "$STATE_ON" ]
        then
            i2cset -y "$CPLD_BUS_NUM" "$CPLD_PWR_CTRL_ADDR" "$OFFSET" "$POW_OFF_SLOT"
            sleep 10
            chassis_status=$(chassis-power-status $SLOT)
            if [ "$chassis_status" -ne "$STATE_OFF" ]
            then
                echo "chassis$CHASSIS_ID power off fail"
                exit 1
            fi
        fi
        i2cset -y "$CPLD_BUS_NUM" "$CPLD_PWR_CTRL_ADDR" "$OFFSET" "$POW_ON_SLOT"
        sleep 2

        # Check chassis stattus after doing 12V cycle
        chassis_status=$(chassis-power-status $SLOT)
        if [ "$chassis_status" == "$STATE_ON" ]
        then
            busctl set-property "$CHASSIS_BUS_NAME""$CHASSIS_ID" "$CHASSIS_OBJ_PATH""$CHASSIS_ID" "$CHASSIS_INTF_NAME" "$CHASSIS_PROPERTY_NAME" s "$CHASSIS_ON"
            exit 0;
        else
            busctl set-property "$CHASSIS_BUS_NAME""$CHASSIS_ID" "$CHASSIS_OBJ_PATH""$CHASSIS_ID" "$CHASSIS_INTF_NAME" "$CHASSIS_PROPERTY_NAME" s "$CHASSIS_OFF"
            exit 0;
        fi
    fi

    echo "Invalid slot id"
    exit 1;
}

if [ "$1" == 0 ]
then
    echo "Enter SLED-cycle"
    result=$(i2cset -y "$CPLD_BUS_NUM" "$CPLD_PWR_CTRL_ADDR" 0x2b 0x1)
    echo "$result"
else
    echo "Enter slot$1 cycle"
    chassis-power-cycle "$1"
fi

